package org.buptsse.ui;

import java.io.IOException;
import java.io.InputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.buptsse.entity.User;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ActionUtils;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.MD5Helper;
import org.buptsse.utils.StreamTool;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends Activity {
	private final String URL_REGISTER = "http://59.64.164.221:8080/Zhiliao/register.do";
	private final String PROJECT_NAME = "Cicade";
	
	private EditText username = null;
	private EditText password = null;
	private EditText repassword = null;
	private User user = null;
	SharedPreferences preferences = null;

	private Button register = null;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case APPConstant.RegistError:
				Toast.makeText(getApplicationContext(), "用户名已被使用", 1000).show();
				break;

			case APPConstant.RegistFinish:
				//Toast.makeText(getApplicationContext(), "finish", 1000).show();
				Intent intent=new Intent();
				intent.setClass(RegisterActivity.this, RegisterOneActivity.class);
				startActivity(intent);
				finish();
				break;
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;
			}
		}
	
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 去掉任务条
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.register);

		
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password_1);
		repassword = (EditText) findViewById(R.id.password_2);
		register = (Button) findViewById(R.id.register_button);
		// back
		Button btBack = (Button) this.findViewById(R.id.back_button);
		btBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent it = new Intent(RegisterActivity.this,
						LoginActivity.class);
				RegisterActivity.this.startActivity(it);
			}
		});
		register.setOnClickListener(new RegisterListener());
	}

	class RegisterListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			//String email = useremail.getText().toString();
			String name = username.getText().toString();
			String psw = password.getText().toString();
			String repsw = repassword.getText().toString();
			if (!psw.equals(repsw)) {
				Toast.makeText(RegisterActivity.this, R.string.inconsist,
						Toast.LENGTH_LONG);
			}
			//执行注册步骤
			RegistThread rt=new RegistThread(name, MD5Helper.MD5Encoded(psw));
			rt.start();
		}
	}
	
	private class RegistThread extends Thread
	{
		private String name,pwd;
		public RegistThread(String name,String pwd)
		{
			this.name=name;
			this.pwd=pwd;
		}
		
		@Override
		public void run()
		{
			if(false==ConnectionChecker.CheckConnection(getApplicationContext(), handler))
			{
				return;
			}
			HttpPost post=new HttpPost(APPConstant.registUrl);
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("username", this.name));
			param.add(new BasicNameValuePair("password", this.pwd));
			try {
				post.setEntity(new UrlEncodedFormEntity(param, "UTF-8"));
				HttpResponse response=new DefaultHttpClient().execute(post);
				HttpEntity entity=response.getEntity();
				InputStream content=entity.getContent();
				String result=StreamTool.convertStreamToString(content);
				//Log.v("RegisterAcitivty", result);
				if(result.equals("success"))
				{
					//注册成功
					Message msg=handler.obtainMessage(APPConstant.RegistFinish);
					handler.sendMessage(msg);
					GloableInstance.user.setName(name);
					GloableInstance.user.setPassword(pwd);
					GloableInstance.user.setLoginState(true);
				}else {
					//注册失败
					Message msg=handler.obtainMessage(APPConstant.RegistError);
					handler.sendMessage(msg);
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public boolean registerAction() {
		//String email = useremail.getText().toString();
		String name = username.getText().toString();
		String psw = password.getText().toString();
		String repsw = repassword.getText().toString();
		/*if (null == email || "".equals(email) || null == email
				|| "".equals(email) || null == email || "".equals(email)
				|| null == email || "".equals(email)) {
			Toast.makeText(RegisterActivity.this, R.string.complete,
					Toast.LENGTH_LONG);
			return false;
		} else {*/
		if (!psw.equals(repsw)) {
			Toast.makeText(RegisterActivity.this, R.string.inconsist,
					Toast.LENGTH_LONG);
		} else {
			//执行注册步骤
		}

		return false;
	}

	public boolean register(String url, String name, String mail,
			String password, String psw) {
		if (password == null || psw == null || !password.equals(psw))
			return false;
		HttpPost request = new HttpPost(url);
		JSONObject param = new JSONObject();
		// StringEntity se = null;
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			param.put("name", name);
			param.put("mail", mail);
			param.put("password", password);
			pair.add(new BasicNameValuePair("register", param.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			// se = new StringEntity(param.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// request.setEntity(se);
		HttpResponse httpResponse = null;
		try {
			httpResponse = new DefaultHttpClient().execute(request);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String responseStr = null;
		try {
			responseStr = EntityUtils.toString(httpResponse.getEntity());
			if (responseStr != null)
				new AlertDialog.Builder(this).setMessage(responseStr).create()
						.show();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (responseStr != null) {
			try {
				JSONObject obj = new JSONObject(responseStr);
				user = new User();
				user.setId(obj.getInt("userid"));
				user.setName(obj.getString("name"));
				user.setFan(obj.getInt("fan"));
				user.setFollow(obj.getInt("follow"));
				user.setPostAmount(obj.getInt("postamount"));
                user.setImage(obj.getString("image"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		if (null == user)
			return false;
		return true;
	}

	void setUserInfo(String name, String psw) {
		SharedPreferences preferences = getSharedPreferences(PROJECT_NAME,
				Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		editor.putBoolean("auto", true);// 是否自动填充
		editor.putString("username", name);
		editor.putString("psw", psw);
		editor.commit();
	}
}